package com.hdu.h_health.news.widget;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hdu.h_health.news.FragmentXAdapter;
import com.hdu.h_health.R;
import com.hdu.h_health.bean.NewsBean;
import com.hdu.h_health.common.BaseFragment;
import com.hdu.h_health.news.view.BaseView;
import com.hdu.h_health.news.presenter.InfoPresenter;
import com.hdu.h_health.news.presenter.InfoPresenterItf;
import com.hdu.h_health.ui.NewsDetailsActivity;
import com.hdu.h_health.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 资讯分类视图--原Fragment2-8
 * Created by 612 on 2016/2/26.
 */
public class NewsListFragment extends BaseFragment implements BaseView<NewsBean>, SwipeRefreshLayout.OnRefreshListener, FragmentXAdapter.OnItemClickListener {
    @Bind(R.id.rc_view)
    RecyclerView rcView;
    @Bind(R.id.sw_refresh)
    SwipeRefreshLayout swRefresh;

    private FragmentXAdapter adapter;

    private List<NewsBean> newsBeans = new ArrayList<>();

    private LinearLayoutManager mLayoutManager;

    private InfoPresenter infoPresenter;

    private boolean isPrepared;//标志Fragment已经初始化完成

    private int mType;//资讯类型

    private int currentPage = 0;//当前页

    //静态工厂方法实例化Fragment
    public static NewsListFragment newInstance(int type) {
        Bundle args = new Bundle();
        NewsListFragment fragment = new NewsListFragment();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        infoPresenter = new InfoPresenterItf(this);//上溯造型，初始化Presenter
        mType = getArguments().getInt("type");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmentx, container, false);
        ButterKnife.bind(this, view);
        initSwRefresh();
        initRecyclerView();
        isPrepared = true;//控件初始化完成
        lazyLoad();//延时加载加载数据——即Fragment可见时
        return view;
    }

    //初始化下拉刷新布局
    private void initSwRefresh() {
        //设置进度条颜色
        swRefresh.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary);
        swRefresh.setOnRefreshListener(this);
    }

    //初始化RecyclerView
    private void initRecyclerView() {
        mLayoutManager = new LinearLayoutManager(getActivity());
        rcView.setLayoutManager(mLayoutManager);
        rcView.setItemAnimator(new DefaultItemAnimator());//设置分隔线
        adapter = new FragmentXAdapter(getActivity(), newsBeans);
        adapter.setOnItemClickListener(this);
        rcView.setAdapter(adapter);
        rcView.addOnScrollListener(mOnScrollListener);
    }

    //RecyclerView滑动监听
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {

        private int lastVisibleItem;//最后一个Item的位置

        //滑动完成
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();//设置最后一个Item的位置
        }

        //滑动状态改变
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            adapter.isShowFooter(true);
            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == adapter.getItemCount()
                    && adapter.isShowFooter()) {
                //调用Presenter层的loadNews方法加载更多
                infoPresenter.loadInfo(getActivity(), currentPage, mType);
            }
        }
    };

    //改变当前页数
    @Override
    public void changePage(int page) {
        this.currentPage = page;
    }

    //显示进度条
    @Override
    public void showProgress() {
        swRefresh.setRefreshing(true);
    }

    //添加数据
    @Override
    public void addData(List<NewsBean> newsList) {
        if (newsList == null) return;
        if (newsBeans == null) newsBeans = new ArrayList<>();
        if (currentPage == 0 && newsList.size() >= 5) adapter.isShowFooter(true);//超过5条即一页新闻时
        if (currentPage == 0 && newsBeans.size() > 0 && newsList.size() > 0) {//下拉刷新并且之前已有数据
            newsBeans.clear();
        } else {
            //TODO　如果没有更多数据了,则隐藏footer布局（隐藏动画生硬）
            if (newsList.size() == 0) {
                CommonUtils.showLog("没有更多了");
                CommonUtils.showToast(getActivity(), "没有更多数据了");
                adapter.isShowFooter(false);
            }
        }
        newsBeans.addAll(newsList);
        adapter.notifyDataSetChanged();
    }

    //隐藏进度条
    @Override
    public void hideProgress() {
        swRefresh.setRefreshing(false);
    }

    //显示错误信息
    @Override
    public void showLoadFailMsg(String error) {
        if (currentPage == 0) {
            adapter.isShowFooter(false);
            adapter.notifyDataSetChanged();
        }
        CommonUtils.showLog(error);
        CommonUtils.showToast(getActivity(), getResources().getString(R.string.NetworkError));
    }

    //下拉刷新
    @Override
    public void onRefresh() {
        currentPage = 0;
        //调用Presenter控制层的loadInfo加载数据
        infoPresenter.loadInfo(getActivity(), currentPage, mType);
    }

    //列表项点击事件
    @Override
    public void onItemClick(View view, int position) {
        NewsBean newsBean = newsBeans.get(position);
        Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
        intent.putExtra(NewsDetailsActivity.URL, newsBean.getUrl());
        startActivity(intent);
    }

    /**
     * Fragment可见时并且控件初始化完成后才调用网络加载数据
     */
    @Override
    protected void lazyLoad() {
        //初始化完成并且可见
        if (!isPrepared || !isVisible) {
            return;
        }
        //判断该Fragment是否是第一次加载数据
        if (newsBeans.size() == 0) {
            //下拉刷新加载数据
            onRefresh();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
